package base.thread_JUC2.chapter02.demo03;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class EventStorage {
    private int maxSize;

    private List<Date> storage;

    public EventStorage (){
        this.maxSize = 10;
        storage = new LinkedList<>();
    }

    public synchronized void set() {
        while (maxSize == storage.size()){
            try {
//                notifyAll();//
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.add(new Date());
        System.out.printf("%s  Set: %d\n", Thread.currentThread().getName(), storage.size());
        notifyAll();// 循环51次后唤醒消费者线程，消费者线程执行完毕后结束
    }

    public synchronized void get() {
        while (storage.size() ==0){
            try {
//                notifyAll();// 消费者线程消费完毕，唤醒生产者，并消费者进入wait，而生产者只剩下最后一次循环，导致生产者不达条件而不会对消费者进行唤醒，这样消费者就进入一直wait，而程序不得退出
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("%s Get: %s, Size: %d\n",Thread.currentThread().getName(), ((LinkedList<Date>)storage).poll(), storage.size());
        notifyAll();//循环51次后唤醒生产者线程，生产者线程执行完毕后结束
    }


}
